package com.turing.data.scripts.yhjftzd.filter

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.TypeReference
import com.turing.common.entity.TextVO
import com.turing.common.util.FileUtils
import com.turing.data.engine.utils.ScriptsUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import org.apache.commons.lang.SerializationUtils

import java.util.regex.Matcher
import java.util.regex.Pattern
import java.util.stream.Collectors

/**
 * 场景名称: 外汇缴费通知单
 * 要素名称: 机构名称
 * @author: fanyihang
 */

class OrganizationNames_30261_66_filter {

    static List< TaskElementVO.DrawResultVO > doConvert(DependParamsVO dependParams){

        List<TaskElementVO.DrawResultVO> trueValueSet = new ArrayList<>()
        List<TaskElementVO.DrawResultVO > resultVOs = ScriptsUtils.tryInitResult(dependParams)
        //使用正则
        String reg = /(?<=机构名称[:：]).+?）/
        dependParams.JSONTextMap.forEach(
                { childTaskSn, jsonText ->
                    TaskElementVO.DrawResultVO drawResultVO = getResultByRegExp(jsonText,childTaskSn,reg,[],[],false,false)
                    trueValueSet.add(drawResultVO)
                }
        )
        if (trueValueSet.size()>0){
            trueValueSet.get(0).businessValue = trueValueSet.get(0).text.replaceAll(/[:：]/,"")
            return trueValueSet
        }

        if(trueValueSet[0].text.equals("")){
            //依赖模型，通过关键词返回值---博普债券1号
            def REGEX_BACKUP_1 = "机构名称"

            if (resultVOs!=null && resultVOs.size()>0) {
                for (int i = 0; i < resultVOs.size(); i++) {
                    def drawResultVO = resultVOs.get(i)
                    def childTaskSn = drawResultVO.childTaskSn
                    if(null == childTaskSn || childTaskSn == ""){
                        continue
                    }
                    def start = drawResultVO.start
                    def end = drawResultVO.end
                    def text = drawResultVO.text
                    text = text.replaceAll("\n","")
                    def textPathMap = dependParams.textPathMap
                    def rawPath = textPathMap.get(drawResultVO.childTaskSn)
                    def rawText = FileUtils.loadJson(rawPath)
                    def expandOffset = 0
                    //往前10个字符搜索
                    while( expandOffset <= 30 && start > expandOffset ){
                        def expandString = rawText.substring(start-expandOffset,start)
                        if( expandString =~ REGEX_BACKUP_1)
                        {
                            drawResultVO.businessValue = drawResultVO.text.replaceAll(/[（）:：]/,"")
                            drawResultVO.setType(1)
                            trueValueSet.add(drawResultVO)
                            return trueValueSet
                        }
                        expandOffset  = expandOffset+10
                    }
                }
            }
        }

        //返回空字符串
        TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
        defaultDrawResultVO.text = ""
        trueValueSet.clear()
        trueValueSet.add(defaultDrawResultVO)
        return  trueValueSet

    }

    //传入json文本; 传入id号 ；正则表达式 ； 前后关键字（是否包括关键字） ；返回抽取结果，不包括关键字
    static TaskElementVO.DrawResultVO getResultByRegExp (String jsonText,String childTaskSn ,String regExp ,List<String> startKeyList,List<String> endKeyList,Boolean startContains,Boolean endContains){
        //创建一个返回对象
        TaskElementVO.DrawResultVO drawResultVO = new TaskElementVO.DrawResultVO();
        //进行对jsonText文件的解析
        List<TextVO> textVOList = JSON.parseArray(jsonText, TextVO.class)
        //每行数据进行遍历拼成整段文本(每页文本)
        StringBuffer stringBuffer = new StringBuffer()
        //开始遍历
        for (i in 0..<textVOList.size()) {
            //获得当前页的段落
            List<TextVO.Paragraph> listParagraph = textVOList[i].paragraphs
            for (j in 0..<listParagraph.size()) {
                //获得每行集合
                List<TextVO.Line> lines = listParagraph[j].lines;
                for (k in 0..<lines.size()) {
                    stringBuffer = stringBuffer.append(lines.get(k).objContent)
                }
            }
        }
        //获得全文本
        String allText = stringBuffer.toString()
        //输入正则
        Pattern pattern = ~regExp
        //拿全文本进行匹配
        Matcher matcher = pattern.matcher(allText)
        //定义一个真正展示的文本
        String valueText = "";
        def start = 0
        def end = 0
        //能匹配到：可以获得文本内容，和匹配内容在全文本起始位置(左闭右开)
        while (matcher.find()){
            valueText = matcher.group(0)
            start = matcher.start()
            end = matcher.end()
            break;
        }

        //没有匹配到直接返回的文本为空字符串
        if(valueText.equals("")){
            drawResultVO.text = ""
            return drawResultVO
        }

        //通过start和end判断返回经过的行号
        //关键词进行偏移(前后均不包括关键字)
        int startOffset = 0
        int endOffset = 0
        String startKey = ""
        String endKey = ""
        //对传入的关键字进行遍历
        if(!startKeyList.isEmpty()){
            for (k in 0..<startKeyList.size()) {
                if (valueText.contains(startKeyList.get(k))){
                    startKey = startKeyList.get(k)
                    break;
                }
            }
        }
        if(!endKeyList.isEmpty()){
            for (k in 0..<endKeyList.size()) {
                if (valueText.contains(endKeyList.get(k))){
                    endKey = endKeyList.get(k)
                    break;
                }
            }
        }

        //根据关键字重新计算起始位置和文本内容
        if(!startKey.equals("")&&valueText.contains(startKey)){
            if(startContains){
                startOffset = valueText.indexOf(startKey)
                start = start+startOffset
            }else {
                startOffset = valueText.indexOf(startKey)+startKey.length()
                start = start+startOffset
            }
        }
        if(!endKey.equals("")&&valueText.contains(endKey)){
            if (endContains){
                endOffset = valueText.lastIndexOf(endKey)+endKey.length() - valueText.length()
                end = end + endOffset
            }else{
                endOffset = valueText.lastIndexOf(endKey) - valueText.length()
                end = end + endOffset
            }
        }
        valueText = valueText.substring(startOffset,valueText.length()+endOffset)
        //装匹配到的行号
        List<String> lineIDs = new ArrayList<>();
        List<Integer> pos_info = new ArrayList<>();

        //通过起始位置：了解在第几页，并拿到该页信息（只支持在同一页）
        int pageId = -1
        List<TextVO.Paragraph> trueParagraphs = new ArrayList<>();
        for (i in 0..<textVOList.size()) {
            //获得当前页的段落
            int pageStartIndex = textVOList.get(i).pageStartIndex
            int pageEndIndex = textVOList.get(i).pageEndIndex
            //在同一页(不在同一页就返回,当前起始位置到该页最后一个字符)
            if(start>=pageStartIndex && end<=pageEndIndex){
                pageId = textVOList.get(i).pageNo;
                trueParagraphs = textVOList.get(i).paragraphs
            }else if(start>=pageStartIndex&&start<pageEndIndex&&end>pageEndIndex){
                end = pageEndIndex
                pageId = textVOList.get(i).pageNo;
                trueParagraphs = textVOList.get(i).paragraphs
            }
        }
        for (j in 0..<trueParagraphs.size()) {
            //获得每行集合
            List<TextVO.Line> lines = trueParagraphs[j].lines;
            //进行遍历
            for (l in 0..<lines.size()) {
                //每行的起止字符的全局位置[indexStart,indexEnd)
                TextVO.Line line = lines.get(l)
                def indexStart = line.lineStartIndex
                def indexEnd = line.lineEndIndex
                //大于等于行起始行,小于结束行
                if(start>=indexStart&&start<indexEnd){
                    lineIDs.add(line.getLineId());
                    pos_info.add(start-indexStart)
                }
                if(start<indexStart&&end>indexEnd){
                    lineIDs.add(line.getLineId());
                }
                if(end>indexStart&&end<=indexEnd){
                    lineIDs.add(line.getLineId());
                    pos_info.add(end-indexStart)
                }
            }
        }

        //对lineIDS进行去重，返回一行时会出现重复问题
        lineIDs = lineIDs.stream().distinct().collect(Collectors.toList())

        //返回最后结果
        drawResultVO.page = pageId
        drawResultVO.setType(1)
        drawResultVO.text = valueText
        drawResultVO.businessValue = valueText
        drawResultVO.start = start
        drawResultVO.end = end
        drawResultVO.childTaskSn = childTaskSn
        drawResultVO.pos_info = pos_info
        drawResultVO.para_info = lineIDs
        return drawResultVO
    }

}
